package com.bbcare.nutritious.plat.service.imp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.SeqUtil;
import com.bbcare.department.plat.service.IBsSmsTemplateService;
import com.bbcare.followup.plat.entity.Patient;
import com.bbcare.followup.plat.service.IFollowQueueService;
import com.bbcare.followup.plat.service.IPatientService;
import com.bbcare.followup.plat.service.ISmsService;
import com.bbcare.nutritious.plat.entity.PtBloodsugarRecord;
import com.bbcare.nutritious.plat.entity.PtDeviceRef;
import com.bbcare.nutritious.plat.service.IBloodSugarService;
import com.bbcare.nutritious.plat.store.ibatis.IBloodSugarDao;

/**
 * 
 * @name:         BloodSugarControllerService.java
 * @author:       tao
 * @createTime:   2017年7月3日
 * @description:  糖尿病  相关服务
 * @modify:
 *
 */
@Service
public class BloodSugarService implements IBloodSugarService {

	public static final Logger logger = Logger.getLogger(BloodSugarService.class);

    @Autowired
    private IBloodSugarDao bloodSugarDao;
    @Autowired
    private IPatientService patientService;
    @Autowired
    private IFollowQueueService fllowQueueService;
    @Autowired 
    private ISmsService smsService;
    @Autowired
    private IBsSmsTemplateService bsSmsTemplateService;

    
	@Override
	@Transactional
	public Map<String, Object> deviceBind(Map<String, Object> map)
			throws Exception {
		Map<String,Object> rspMap = new HashMap<String,Object>();
		String userId = (String)map.get("userId");
		String tenantId = (String)map.get("tenantId");
		String deviceId = (String)map.get("deviceId");
		String authorId = (String)map.get("authorId");
		String type = (String)map.get("type");
		
		if(!Constants.DEVICE_TYPE_SPORT.equals(type)){
			type = Constants.DEVICE_TYPE_BLOOD;//不传或其他不正确类型  默认为血糖
		}
		
		//判断用户是否存在 
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("userId",userId);
		paramMap.put("tenantId",tenantId);
		Patient pt = patientService.getPatient(paramMap);
		if(null == pt){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,
	        			"患者信息不存在");
		}
		
		//判断设备是否存在 ---
		
		//判断设备是否已经被绑定 
		paramMap.clear();
		paramMap.put("deviceId",deviceId);
		paramMap.put("status",Constants.COMMON_STATUS_NOMAL);
		paramMap.put("type",type);
		paramMap.put("tenantId",tenantId);
		List<Map<String,Object>> deviceRefList = bloodSugarDao.selectDeviceRefList(paramMap);
		if(!CollectionUtils.isEmpty(deviceRefList)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_DEVICE_HAS_BINDED,"设备已经绑定到其他用户");
		}  
		
		//
		paramMap.clear();
		paramMap.put("userId",userId);
		paramMap.put("status",Constants.COMMON_STATUS_NOMAL);
		paramMap.put("type",type);
		paramMap.put("tenantId",tenantId);
		List<Map<String,Object>> deviceUserList = bloodSugarDao.selectDeviceRefList(paramMap);
		if(!CollectionUtils.isEmpty(deviceUserList)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_USER_HAS_BINDED,"用户已经绑定其他设备");
		}
		
		List<PtDeviceRef> list = new ArrayList<PtDeviceRef>();
		PtDeviceRef ref = new PtDeviceRef();
		ref.setId(SeqUtil.getSeqNo());
		ref.setCreateAuthor(authorId);
		ref.setDeviceId(deviceId);
		ref.setStatus(Constants.COMMON_STATUS_NOMAL);
		ref.setType(type);
		ref.setUserId(userId);
		ref.setCreateTime(DateUtil.getSysDateA());
		ref.setTenantId(tenantId);
		list.add(ref);
		if(!CollectionUtils.isEmpty(list)){
			bloodSugarDao.saveDevieRef(list);
		}
		
		//根据绑定是否是华米手环  是否发送短信
		/*if(Constants.DEVICE_TYPE_SPORT.equals(type)){//小米手环 绑定后 需要授权
			Map<String,Object> urlMap= new HashMap<String,Object>();
			urlMap.put("userId",userId);
			urlMap.put("tenantId",tenantId);
			urlMap.put("deviceId",deviceId);
//			String url = HuamitechApiUtil.buildHuamiUrl(urlMap);
			String url = HuamitechApiUtil.buildForwordUrl(urlMap);
			
			// 发消息到 患者注册 消息队列topic 放在最后处理
	        Map<String, Object> smsMap = new HashMap<String, Object>();
	        smsMap.put("tenantId", tenantId);
	        smsMap.put("code", Constants.SMS_TEMPLATE_HMSQDX_TYPE);
	        String smsContent = bsSmsTemplateService.getSmsTemplateByCondition(smsMap);
	        if(!StringUtils.isEmpty(smsContent)){
	        	smsContent = smsContent.replace("\\$\\{URL\\}",url);
	        	
	        	Map<String, Object> msgMapIn = new HashMap<String, Object>();
	            msgMapIn.put("authorId", authorId);
	            msgMapIn.put("updateTime",DateUtil.getSysDateA());
	            msgMapIn.put("phoneNo", pt.getPhoneNo());
//	            msgMapIn.put("ptSchemeid", ptSchemeid);
//	            msgMapIn.put("queueId", queueId);
	            msgMapIn.put("userId", userId);
	            msgMapIn.put("ruleType", Constants.FU_INFORM_RULE_TYPE_SMS);
	            msgMapIn.put("smsType","05");// 促销短信
	            msgMapIn.put("smsText", smsContent);
	            msgMapIn.put("tenantId",tenantId);
	            // 改为调用内部接口 	//发送短信 
	            smsService.saveSmsInfo(msgMapIn);
	            logger.info("短信入实时短信发表成功");
	        }
			
		}*/
		return rspMap;
	}
	
	@Override
	@Transactional
	public Map<String, Object> deviceUnbind(Map<String, Object> map)
			throws Exception {
		Map<String,Object> rspMap = new HashMap<String,Object>();
		String id = (String)map.get("id");
		String authorId = (String)map.get("authorId");
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("status", Constants.COMMON_STATUS_DELETE);
		paramMap.put("id", id);
		paramMap.put("updateAuthor", authorId);
		paramMap.put("updateTime", DateUtil.getSysDateA());
		bloodSugarDao.updateDevieRef(paramMap);
		
		//华米手环解绑后  授权也解除  不在同步手环数据
		
		return rspMap;
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public Map<String, Object> bloodsugarImport(Map<String, Object> map)
			throws Exception {
		logger.info("bloodsugarImport in ");
		
		String tenantId =(String)map.get("tenantId");
		//根据设备ID 查询  userId 转换
		
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("type", Constants.DEVICE_TYPE_BLOOD);
		param.put("status",Constants.COMMON_STATUS_NOMAL);
		param.put("tenantId", tenantId);
		List<Map<String,Object>> reflist = bloodSugarDao.selectDeviceRefList(param);
		Map<String,String> deviceRefMap = new HashMap<String,String>();
		if(!CollectionUtils.isEmpty(reflist)){
			for(int i = 0 ;i<reflist.size();i++){
				deviceRefMap.put(reflist.get(i).get("deviceId").toString(),reflist.get(i).get("userId").toString());
			}
		}
		
		//防止 没有绑定用户情况下 上传也将数据 入表  
		List<PtBloodsugarRecord> list =(List<PtBloodsugarRecord>)map.get("list");
		if(!CollectionUtils.isEmpty(list)){
			for(int i  = 0 ;i<list.size();i++){
				String deviceId = list.get(i).getDeviceId();
				if(deviceRefMap.containsKey(deviceId) && null != deviceRefMap.get(deviceId)){
					list.get(i).setUserId(deviceRefMap.get(deviceId));
				}else{
					list.get(i).setRemark1("还未绑定用户");
				}
				list.get(i).setTenantId(tenantId);
			}
			bloodSugarDao.saveBloodsugarRecord(list);
		}
		
		logger.info("bloodsugarImport out ");
		return null;
	}
	
	@Override
	public List<Map<String, Object>> getRecordPatientList(
			Map<String, Object> paramMap) throws Exception {

		List<Map<String, Object>>  list = new ArrayList<Map<String, Object>>();
		String queueId  = ((paramMap.get("queueId")!=null && !StringUtils.isEmpty(paramMap.get("queueId").toString()))) ? paramMap.get("queueId").toString() : null;
		
		List<String> queueIdArray = new ArrayList<String>();
		if(StringUtils.isEmpty(queueId)){
			// 根据当前登录账号获取，其可以查看的队列id
			queueIdArray = fllowQueueService.getQueueArrByAuthority(paramMap);
			if(CollectionUtils.isEmpty(queueIdArray)){
				logger.warn("该账号无可查看到的患者信息...arg==" + paramMap.toString());
				return list;
			}
		}else{
			queueIdArray.add(queueId);
		}
		
        paramMap.put("queueIdIn",queueIdArray);
        paramMap.put("userStatus",Constants.QUEUE_STATUS_NOMAL);
        
		int page =  (paramMap.get("page")!=null && !StringUtils.isEmpty(paramMap.get("page").toString())) ? Integer.parseInt(paramMap.get("page").toString()) : 1;
		int rows =  (paramMap.get("rows")!=null && !StringUtils.isEmpty(paramMap.get("rows").toString())) ? Integer.parseInt(paramMap.get("rows").toString()) : 10;
		
		paramMap.put("start", rows*(page-1));
		paramMap.put("end", rows);
		
		Object userNameObject = paramMap.get("searchCondition");
		Object searchCondition = (userNameObject!=null &&!StringUtils.isEmpty(userNameObject)) ? "%"+userNameObject.toString()+"%" : userNameObject ; 

		paramMap.put("searchCondition",searchCondition);
		list = bloodSugarDao.selectBloodsugarPatientList(paramMap);
		Map<String, Object> map =null;
		if(!CollectionUtils.isEmpty(list)){
			for(int i = 0;i<list.size();i++){
				map = list.get(i);
				//监测时间
				list.get(i).put("testTime",map.get("testTime").toString());
				//录入时间
				list.get(i).put("testTimeDesc",DateUtil.formatTimedifference(map.get("createTime").toString()));
				map = null;
			}
		}
		return list;
	}

	@Override
	public int getRecordPatientCount(Map<String, Object> paramMap)
			throws Exception {
		paramMap.put("userStatus",Constants.QUEUE_STATUS_NOMAL);
		return bloodSugarDao.selectBloodsugarPatientCount(paramMap);
	}
	
	@Override
	public Map<String, Object> getRecordListByUserId(
			Map<String, Object> paramMap) throws Exception {
		Map<String,Object> rspMap = new HashMap<String,Object>();
		Map<String,Object>  usermap = new HashMap<String,Object>();
		usermap.put("userId", paramMap.get("userId"));
		usermap.put("tenantId", paramMap.get("tenantId"));
//		map.put("status","1"));
		Patient patient = patientService.getPatient(usermap);
		
		if(null == patient){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,
        			"患者信息不存在");		}
		rspMap.put("birthday",patient.getBirthday());
		rspMap.put("pregnancyWeek",patient.getPregnancyDay());
		rspMap.put("userName",patient.getUserName());
		rspMap.put("gender",patient.getGender());
		rspMap.put("phoneNo",patient.getPhoneNo());
		rspMap.put("userId",paramMap.get("userId"));
		
		//查询绑定设备和状态 
		usermap.clear();
		usermap.put("userId",paramMap.get("userId"));
		usermap.put("status",Constants.COMMON_STATUS_NOMAL);
		usermap.put("type",Constants.DEVICE_TYPE_BLOOD);
		usermap.put("tenantId",paramMap.get("tenantId"));
		List<Map<String,Object>> deviceRefList = bloodSugarDao.selectDeviceRefList(usermap);
		if(CollectionUtils.isEmpty(deviceRefList)){
			rspMap.put("bindStatus", "0");
		}else{
			rspMap.put("bindStatus", deviceRefList.get(0).get("status"));
			rspMap.put("deviceId", deviceRefList.get(0).get("deviceId"));
			rspMap.put("id", deviceRefList.get(0).get("id"));
		}
		
		int page =  (paramMap.get("page")!=null && !StringUtils.isEmpty(paramMap.get("page").toString())) ? Integer.parseInt(paramMap.get("page").toString()) : 1;
		int rows =  (paramMap.get("rows")!=null && !StringUtils.isEmpty(paramMap.get("rows").toString())) ? Integer.parseInt(paramMap.get("rows").toString()) : 10;
		
		paramMap.put("start", rows*(page-1));
		paramMap.put("end", rows);
		
		List<Map<String, Object>>  list = bloodSugarDao.selectBloodsugarList(paramMap);
		
		String testTime = null;
		Map<String, Object> map =null;
		if(!CollectionUtils.isEmpty(list)){
			for(int i = 0;i<list.size();i++){
				map = list.get(i);
				if(null != map.get("testTime")){
					testTime = map.get("testTime").toString();
					list.get(i).put("testTime",DateUtil.getTimeStampSec(testTime));
					list.get(i).put("createTime",DateUtil.getTimeStampSec(testTime));
				}
				map = null;
			}
		}
		
		rspMap.put("recordList", list);
		return rspMap;
	}
	
	

	@Override
	public List<Map<String, Object>> getDeviceList(Map<String, Object> paramMap) throws Exception {

		List<Map<String, Object>>  list = new ArrayList<Map<String, Object>>();
		int page =  (paramMap.get("page")!=null && !StringUtils.isEmpty(paramMap.get("page").toString())) ? Integer.parseInt(paramMap.get("page").toString()) : 1;
		int rows =  (paramMap.get("rows")!=null && !StringUtils.isEmpty(paramMap.get("rows").toString())) ? Integer.parseInt(paramMap.get("rows").toString()) : 10;
		
		paramMap.put("start",page);
		paramMap.put("end",rows);

		Object userNameObject = paramMap.get("userName");
		Object userName = (userNameObject!=null &&!StringUtils.isEmpty(userNameObject)) ? "%"+userNameObject.toString()+"%" : userNameObject ; 
		paramMap.put("userName",userName);
		
		paramMap.put("refStatus",Constants.COMMON_STATUS_NOMAL);
		list = bloodSugarDao.selectDeviceList(paramMap);
		return list;
	}

	@Override
	public int getDeviceCount(Map<String, Object> paramMap)
			throws Exception {
		paramMap.put("userStatus",Constants.QUEUE_STATUS_NOMAL);
		return bloodSugarDao.selectDeviceCount(paramMap);
	}
}
